package main

import (
	"fmt"
	"github.com/spf13/viper"
	"log"
	"strconv"
	"sync"
	"yundian/internel/app/models/users"
	"yundian/internel/pkg/dbs"
	"yundian/internel/pkg/dingo"
	"yundian/internel/pkg/dingo/global"
	"yundian/internel/pkg/utils"
	"yundian/internel/pkg/wechatpay"
)

func main()  {
	dingo.InitViper("./configs/adm.yaml")
	dbs.NewMysqlComponent().Step()

	//var wg sync.WaitGroup
	//for i := 100001; i <= 100000; i++ {
	//	for j := 1; j <= 21; j++ {
	//		wg.Add(1)
	//		ok,_ := utils.PathExists(fmt.Sprintf("./cmd/grawl/data/dividends/20210128/%s-%d.json", strconv.Itoa(i), j))
	//		if ok {
	//			go func(i,j int) {
	//				defer wg.Done()
	//				taskDividends(i, j, "./cmd/grawl/data/dividends/20210128")
	//			}(i,j)
	//		} else {
	//			continue
	//		}
	//	}
	//}
	//wg.Wait()

	//var wg sync.WaitGroup
	//for i := 100067; i <= 100067; i++ {
	//	for j := 1; j <= 3; j++ {
	//		wg.Add(1)
	//		ok,_ := utils.PathExists(fmt.Sprintf("./cmd/grawl/data/dividends/20210128/%s-%d.json", strconv.Itoa(i), j))
	//		if ok {
	//			go func(i,j int) {
	//				defer wg.Done()
	//				taskDividends(i, j, "./cmd/grawl/data/dividends/20210128")
	//			}(i,j)
	//		} else {
	//			continue
	//		}
	//	}
	//}
	//wg.Wait()

	var wg sync.WaitGroup
	for i := 100950; i <= 100950; i++ {
		for j := 2; j <= 3; j++ {
			wg.Add(1)
			ok,_ := utils.PathExists(fmt.Sprintf("./data/dividends/20210407174137/%s-%d.json", strconv.Itoa(i), j))
			if ok {
				go func(i,j int) {
					defer wg.Done()
					taskDividends(i, j, "./data/dividends/20210407174137")
				}(i,j)
			} else {
				continue
			}
		}
	}
	wg.Wait()

}

func taskDividends(id, i int, path string)  {
	userId := strconv.Itoa(id)
	um := users.New()
	global.Orm.Table("users").Where("id = ?", id).Find(um)
	lists := new(settLogGenerated)
	viper.SetConfigFile(fmt.Sprintf(path + "/%s-%d.json", userId, i))
	if err := viper.ReadInConfig(); err != nil {
		log.Fatal("viper.ReadInConfig failed : ", err.Error())
	}
	// 反序列化到struct
	if err := viper.Unmarshal(lists); err != nil {
		log.Fatal("viper.Unmarshal failed : ", err.Error())
	}

	var ccount,ucount int
	for _,lst := range lists.Body.Data {
		//orderInfo := orders.New()
		//global.Orm.Table("orders").Where("trade_no = ?",lst.TradeNo).Find(orderInfo)

		m := &dividendsLogs{}
		//m.Id = lst.ID
		m.TradeNo = lst.TradeNo
		m.Money = int64(lst.Money)
		m.MoneyStr = lst.MoneyStr
		//m.PayMoney = orderInfo.PayMoney
		//m.PayMoneyStr = orderInfo.PayMoneyStr
		m.SettlementMoney = int64(lst.SettlementMoney)
		m.SettlementMoneyStr = lst.SettlementMoneyStr

		m.ProfitType = int8(lst.ProfitType)
		m.ProfitProportion = int8(lst.ProfitProportion)

		m.DeviceSn = lst.DeviceSn
		m.SharedMode = lst.SharedMode
		m.FeeMode = int8(lst.FeeMode)
		m.DeviceTypeID = lst.DeviceTypeID
		m.DeviceTypeName = lst.DeviceTypeName

		m.UserId = lst.UserID
		m.UserName = lst.UserName
		m.PlaceId = lst.PlaceID
		m.PlaceName = lst.PlaceName
		//m.MemberId = orderInfo.MemberId
		//m.MemberName = orderInfo.MemberName

		m.State = int8(lst.State)

		m.CreateAt = dingo.Time(wechatpay.StrTimeToInt(lst.CreateDate))
		m.UpdateAt = dingo.Time(wechatpay.StrTimeToInt(lst.UpdateDate))

		//var count int64
		ccount++
		global.Orm.Table("dividends_log_th").Create(m)  //新增
		//global.Orm.Table("dividends_log").
		//	Where("trade_no = ?", lst.TradeNo).
		//	Where("user_id = ?", lst.UserID).
		//	Where("place_id = ?", lst.PlaceID).Count(&count)
		//if count > 0 {
		//	ucount++
		//	global.Orm.Table("dividends_log").Where("trade_no = ?", lst.TradeNo).
		//		Where("user_id = ?", lst.UserID).
		//		Where("place_id = ?", lst.PlaceID).Model(&m).Updates(m)
		//} else {
		//	ccount++
		//	global.Orm.Table("dividends_log").Create(m)  //新增
		//}
	}
	fmt.Printf("用户:%s(%s)当前页-%d,新增%d条,更新%d条 \n",um.Name,userId,i,ccount,ucount)
}

type dividendsLogs struct {
	Id                 int        `gorm:"column:id" json:"id"`
	TradeNo            string     `gorm:"column:trade_no" json:"tradeNo"`
	// 价格相关
	Money              int64    `gorm:"column:money" json:"money"`
	MoneyStr           string     `gorm:"column:money_str" json:"moneyStr"`
	PayMoney           int64      `gorm:"column:pay_money" json:"payMoney"`               // 支付金额 - 单位分
	PayMoneyStr        string     `gorm:"column:pay_money_str" json:"payMoneyStr"`        //
	SettlementMoney    int64      `gorm:"column:settlement_money" json:"settlementMoney"`
	SettlementMoneyStr string     `gorm:"column:settlement_money_str" json:"settlementMoneyStr"`
	// 分润信息
	ProfitType         int8       `gorm:"column:profit_type" json:"profitType"`
	ProfitProportion   int8       `gorm:"column:profit_proportion" json:"profitProportion"`
	// 设备信息
	DeviceSn           string     `gorm:"column:device_sn" json:"deviceSn"`
	SharedMode         string     `gorm:"column:shared_mode" json:"sharedMode"`
	FeeMode            int8       `gorm:"column:fee_mode" json:"feeMode"`
	DeviceTypeID       int        `gorm:"column:device_type_id" json:"deviceTypeId"`
	DeviceTypeName     string     `gorm:"column:device_type_name" json:"deviceTypeName"`
	// 用户信息
	UserId             int        `gorm:"column:user_id" json:"userId"`
	UserName           string     `gorm:"column:user_name" json:"userName"`
	PlaceId            int        `gorm:"column:place_id" json:"placeId"`
	PlaceName          string     `gorm:"column:place_name" json:"placeName"`
	MemberId           string     `gorm:"column:member_id" json:"memberId"`
	MemberName         string     `gorm:"column:member_name" json:"memberName"`
	// 状态
	State              int8       `gorm:"column:state" json:"state"`
	// 时间
	PayAt              dingo.Time `gorm:"column:pay_at" json:"payAt"`
	SettlementAt       dingo.Time `gorm:"column:settlement_at" json:"settlementAt"`
	CreateAt           dingo.Time `gorm:"column:create_at" json:"createAt"`
	UpdateAt           dingo.Time `gorm:"column:update_at" json:"updateAt"`

	IsTianHai          int8 `gorm:"column:is_tianhai" json:"-"`

}

type settLogGenerated struct {
	Code int `json:"code"`
	Body struct {
		Total int `json:"total"`
		Data  []struct {
			ID                 int    `json:"id"`
			TradeNo            string `json:"tradeNo"`
			UserID             int    `json:"userId"`
			UserName           string `json:"userName"`
			PlaceID            int    `json:"placeId"`
			PlaceName          string `json:"placeName"`
			DeviceSn           string `json:"deviceSn"`
			SharedMode         string `json:"sharedMode"`
			FeeMode            int    `json:"feeMode"`
			DeviceTypeID       int    `json:"deviceTypeId"`
			DeviceTypeName     string `json:"deviceTypeName"`
			RoleType           int    `json:"roleType"`
			ProfitType         int    `json:"profitType"`
			ProfitProportion   int    `json:"profitProportion"`
			Money              int    `json:"money"`
			SettlementMoney    int    `json:"settlementMoney"`
			State              int    `json:"state"`
			UpdateDate         string `json:"updateDate"`
			CreateDate         string `json:"createDate"`
			MoneyStr           string `json:"moneyStr"`
			ProfitTypeName     string `json:"profitTypeName"`
			SettlementMoneyStr string `json:"settlementMoneyStr"`
			WalletType         int    `json:"walletType"`
			RoleTypeName       string `json:"roleTypeName"`
		} `json:"data"`
	} `json:"body"`
}